﻿using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static NewLife.Remoting.ApiHttpClient;

namespace Framework.WebApi.CorsAccessor;

/// <summary>
/// 跨域设置
/// </summary>
public static class CorsAccessorExtension
{
    /// <summary>
	/// 添加跨域访问
	/// </summary>
	public static void AddCorsAccessor(this IServiceCollection serviceCollection)
	{
		// 读 跨域 配置
		string[] corsUrls = App.GetConfig<string[]>("corsUrls");

		//配置跨域
		serviceCollection.AddCors(c =>
		{
			c.AddPolicy("Policy", policy =>
			{
				policy.WithOrigins(corsUrls ?? Array.Empty<string>())
				.AllowAnyHeader()//允许任意头
				.AllowCredentials()//允许cookie
				.AllowAnyMethod();//允许任意方法
								  // AllowAnyOrigin表示允许任何域；
			});
		});
	}

	/// <summary>
	/// 配置CORS中间件
	/// </summary>
	/// <param name="webApplication"></param>
	public static void UseCorsAccessor(this IApplicationBuilder webApplication)
	{
		// 配置CORS中间件，Policy为策略名称
		// UseCors 必须在 UseRouting 之后，UseResponseCaching、UseAuthorization 之前
		webApplication.UseCors("Policy");
	}
}